package com.rytong.tools.ui;

import android.app.Activity;
import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.LinearGradient;
import android.graphics.Paint.Style;
import android.graphics.Path;
import android.graphics.RectF;
import android.graphics.Shader;
import android.view.KeyEvent;
import android.view.MotionEvent;
import android.view.inputmethod.InputMethodManager;
import android.widget.CheckBox;
import android.widget.TextView;
import com.rytong.tools.ui.Component;
import com.rytong.tools.ui.CssStyle;
import com.rytong.tools.utils.LPToastUtil;
import com.rytong.tools.utils.Utils;

public class LPCheckBox extends Component {
    private static final int TEXT_MARGIN = 5; // will add image width
    private Bitmap checkedImg_;
    private Bitmap unCheckedImg_;
    private Activity activity_;
    
    // 图标的默认宽度。
    private static final int BG_WIDTH_ = Utils.getScaledValueX(35);

    public class MyLPCheckBox extends CheckBox implements CompositedComponent {

        public MyLPCheckBox(Context context, String value) {
            super(context);
            setFocusable(true);
            setFocusableInTouchMode(true);
            setText(value);
            
            setOnEditorActionListener(new OnEditorActionListener() {
				
				@Override
				public boolean onEditorAction(TextView arg0, int arg1, KeyEvent arg2) {
					 InputMethodManager imm = (InputMethodManager) getActivity().getSystemService(
		                        Context.INPUT_METHOD_SERVICE);
		                // 对getCurrentFocus()做不为空判断，避免退出提示框上点击‘确定’和‘取消’按钮报空指针异�导致程序崩�
		                if (null != imm && getActivity().getCurrentFocus() != null) {
		                    // 关闭键盘
		                    imm.hideSoftInputFromWindow(getActivity().getCurrentFocus().getApplicationWindowToken(),
		                            InputMethodManager.HIDE_NOT_ALWAYS);

		                }
					return true;
				}
			});
            if (null != getPropertyByName("checked") && getPropertyByName("checked").equals("checked")) {
            	//先读取报文checked 属性
            	if (null != getPropertyByName("checked")) {
            	    if(getPropertyByName("checked").equals("checked")){
            	        setChecked(true);
            	        setPropertyByName("checked", "true");
            	    } else {
            	        setPropertyByName("checked", "false");
            	    }
            	} else {
            	    //报文没有给checked属性时
            	    setPropertyByName("checked", "false");
            	}
            }
        }

        @Override
        protected void onDraw(Canvas canvas) {
            int posX = 0;
            int posY = 0;

            Bitmap temp = null;
            if (null != checkedImg_ && unCheckedImg_ != null) {
                temp = drawIconByImage(canvas, posX, (height_ - checkedImg_.getHeight()) / 2, temp);
            } else { // 客户端没有多选框图片，进行代码绘制
            	if(paint_ == null){
            		paint_ = getPaint();
            	}
                drawIconManual(canvas, posX);
            }
            /*
             * paint text.
             */
            drawText(canvas, posX, temp);
        }

        /**
         * @param canvas
         * @param posX
         * @param lp
         * @param temp
         */
        private void drawText(Canvas canvas, int posX, Bitmap temp) {
            int posY;
            if (null == temp) {
                posX = TEXT_MARGIN;
            } else {
                posX += temp.getWidth() + TEXT_MARGIN;
            }
            // 如果有多行文字，就进行分行绘制。
            if(stringArr_ != null && stringArr_.length > 1){
            	// int text_height = (int) paint_.getTextSize();// 文字高度
                int text_height = ((int) (getPaint().getTextSize() * 3)) >> 2;
                int length = stringArr_.length;
                // 初始高度为留白高+字高
                float coordinate_y = Utils.getScaledValueY(blankY_) + text_height;
                /**
                 * 多行文字呈自然段，需要进行字间距的绘制。
                 */
                float charPadding = 0;
                for (int i = 0; i < length; i++) {
                	if(stringArr_[i].endsWith("\n")){
        				charPadding = (maxLineWidth_ - 
        						getPaint().measureText(stringArr_[i].substring(0, stringArr_[i].lastIndexOf("\n")))) /
        						(stringArr_[i].substring(0, stringArr_[i].lastIndexOf("\n")).length() - 1);
        			} else {
        				charPadding = (maxLineWidth_ - getPaint().measureText(stringArr_[i])) / (stringArr_[i].length() - 1);
        			}
                	if(i == length - 1 || stringArr_[i].endsWith("\n")){ // 最后一行和自然段尾行不计算字间距。
        				charPadding = 0;
        			}
                    if (i > 0)
                        coordinate_y += text_height + Utils.getScaledValueY(SPACE_Y_);
                    char[] charArray = stringArr_[i].toCharArray();
					for (int j = 0; j < charArray.length; j++) {
						if(charArray[j] != '\n'){
							if(j == 0){
								canvas.drawText(charArray, j, 1, posX, coordinate_y, getPaint());
							} else {
								canvas.drawText(charArray, j, 1, 
										posX + charPadding * j + getPaint().measureText(stringArr_[i].substring(0, j)), 
										coordinate_y, getPaint());
							}
						}
					}
					charArray = null;
//                    canvas.drawText(stringArr_[i], posX, coordinate_y, getPaint());
                }
            } else {
            	String text_ = getPropertyByName("text");
            	posY = (int) (getHeight() + getPaint().getTextSize()) >> 1;
            	if (text_ != null) {
            		canvas.drawText(Utils.abbrevString(text_, getPaint(), width_ - TEXT_MARGIN ), 
            				posX, posY, getPaint());
            	}
            }
        }

        /**
         * @param canvas
         * @param posX
         * @param posY
         * @param temp
         * @return
         */
        private Bitmap drawIconByImage(Canvas canvas, int posX, int posY, Bitmap temp) {
            // 如果客户端保留有多选框图片，则以图片绘制
            try {
                if (this.isChecked()) {
                    temp = checkedImg_;
                } else {
                    temp = unCheckedImg_;
                }
                canvas.drawBitmap(temp, posX, posY, getPaint());
            } catch (Exception ex) {
                Utils.printException(ex);
            }
            return temp;
        }

        /**
         * @param canvas
         * @param posX
         */
        private void drawIconManual(Canvas canvas, int posX) {
            int x = posX;
            int h = (int) paint_.getTextSize();
            int y = h >> 3; 
            int w = h;
            // 圆角矩形圆角弧度
            int radian = 10;
            // 控件未获得焦点
            Shader shader;
            if (this.isChecked()) {
                shader = new LinearGradient(0, y, 0, y + h, new int[] { Color.WHITE, Color.DKGRAY }, null,
                        Shader.TileMode.MIRROR);
            } else {
                shader = new LinearGradient(0, y, 0, y + h, new int[] { Color.DKGRAY, Color.WHITE }, null,
                        Shader.TileMode.MIRROR);
            }
            // 绘制框背景
            paint_.setShader(shader);
            paint_.setStyle(Style.FILL);
            canvas.drawRoundRect(new RectF(x, y, x + w, y + h), radian, radian, paint_);

            // 清空渐变效果
            paint_.setShader(null);
            paint_.setColor(Color.DKGRAY);

            if (this.isChecked()) {
                // 绘制选中后的勾图标
                Path p = new Path();
                int w1 = w >> 1;
                int w2 = w >> 2;
                int w3 = w >> 3;
                int h1 = h >> 1;
                int h2 = h >> 2;
                int h3 = h >> 3;
                p.moveTo(x + w2, y + h1 - h3);
                p.lineTo(x + w1 - 2, y + h1 + h3);
                p.cubicTo(x + w1 - 2, y + h1 + h3, x + 3 * w2, y + h / 6, x + w + w2, y - h2);
                p.cubicTo(x + w + w2, y - h2, x + w + w2, y + h2 - 1, x + w + w2 + 3, y + h2);
                p.cubicTo(x + w + w2 + 3, y + h2, x + 7 * w3 - 2, y + 3 * h3 - 1, x + w1 - 2, y + h);
                p.cubicTo(x + w1 - 2, y + h, x + w3, y + 5 * h3, x - 3, y + h1 + 2);
                p.close();
                canvas.drawPath(p, paint_);
            }
            if (this.isFocused()) {
                // 用单色绘制外包围选择框
                paint_.setStyle(Style.STROKE);
                canvas.drawRoundRect(new RectF(x - 1, y - 1, x + w + 1, y + h + 1), radian, radian, paint_);
            }
        }

        @Override
        public Component composited() {
            return LPCheckBox.this;
        }

        @Override
        public boolean onTouchEvent(MotionEvent event) {
            boolean isAction = false;
            int touchEvent = event.getAction();
            switch (touchEvent) {
            case MotionEvent.ACTION_DOWN:
            	// 按下tr时候变色。
            	trDownColor(tr_, llvSV_);
                isAction = true;
                isAction = super.onTouchEvent(event);
                break;
            case MotionEvent.ACTION_MOVE:
            	// 移动tr恢复颜色。
            	int offset = (int) Math.abs(yDown_ - event.getY());
            	if (offset > offset_) {
            		trMoveColor(tr_, llvSV_);
            	}
                break;
            case MotionEvent.ACTION_UP:
            	// 抬起tr恢复颜色。
            	trUpColor(tr_, llvSV_);
                if (isChecked()) {
                    setCheckedBox(false);
                    setPropertyByName("checked", "false");
                } else {
                    setCheckedBox(true);
                    setPropertyByName("checked", "true");
                }
                setVisibleInvisible(isChecked());
                isAction = onClick((String) composited().property_.get("onclick"));
                invalidate();
                break;
            default:
                isAction = super.onTouchEvent(event);
            }
            return isAction;
        }

    }
    
    /**
     * 控件联动方法
     * @param lpSelect
     * @param option
     */
    public void setVisibleInvisible(boolean isChecked){
    	//复选框按钮比较特殊，选中和非选中的状态
    	if(LPToastUtil.getInstance().isBranchBank){
    		String invisible = null;
    		String visible = null;
    		if(isChecked){
    			invisible = getPropertyByName("invisible");
    			visible = getPropertyByName("visible");
    		}else{
    			visible = getPropertyByName("invisible");
    			invisible = getPropertyByName("visible");
    		}
    		Utils.setCompontentsLinked(visible, invisible);
    	}
    }
    
    @Override
    public void mouldH() throws Exception {
        super.mouldH();
        setCheckBoxIcons();
        if(checkedImg_ != null && unCheckedImg_ != null){
        	reSetTextLayoutParams(checkedImg_.getWidth() + TEXT_MARGIN);
        }
        
        if(null != cssStyle_){
        	mouldCssStyle();        	
        }
    }
    
    @Override
    public void mouldCssStyle() {
        if (cssStyle_.getPropertyIndex(CssStyle.BGIMAGEURL) > cssStyle_.getPropertyIndex(CssStyle.BACKGROUNDCOLOR)) {
            setBackgroundDrawableByCssStyle();
        } else {
            setBackgroundColorByCssStyle();
        }
    }

    /** create check box images */
    public void setCheckBoxIcons() {
    	if(checkedImg_ == null || unCheckedImg_ == null){
    	    if(getContext() != null){
    	        int checkedImg_Id = Utils.getResourcesId(getContext(), "checkbox_checked", "drawable");
    	        checkedImg_ = Utils.getBitmap(checkedImg_Id, activity_);
    	        int unCheckedImg_Id = Utils.getResourcesId(getContext(), "checkbox_unchecked", "drawable");
    	        unCheckedImg_ = Utils.getBitmap(unCheckedImg_Id, activity_);
    	    }
    	}
    	
		if (checkedImg_ != null && unCheckedImg_ != null) {
			checkedImg_ = Bitmap.createScaledBitmap(checkedImg_,
					Utils.getScaledValueX(checkedImg_.getWidth()),
					Utils.getScaledValueX(checkedImg_.getHeight()), true);
			unCheckedImg_ = Bitmap.createScaledBitmap(unCheckedImg_,
					Utils.getScaledValueX(unCheckedImg_.getWidth()),
					Utils.getScaledValueX(unCheckedImg_.getHeight()), true);
		}
    }

    /**
     * @param isChecked
     */
    private void setCheckedBox(boolean isChecked) {
        if (realView_ == null) {
            return;
        }
        MyLPCheckBox checkBox = (MyLPCheckBox) realView_;
        checkBox.setChecked(isChecked);
    }

    /**
     * @return
     */
    public boolean isChecked() {
        if (null != realView_) {
            MyLPCheckBox temp = (MyLPCheckBox) realView_;
            return temp.isChecked();
        }
        return false;
    }

    @Override
    public void initRealView(Activity activity, String value) {
        super.initRealView(activity, value);
        activity_ = activity;
        realView_ = new MyLPCheckBox(activity, value);
    }

    @Override
    public void releaseResource(Component component) {
    	// TODO Auto-generated method stub
    	super.releaseResource(component);
    	Utils.releaseObject(checkedImg_);
    	Utils.releaseObject(unCheckedImg_);
    }
}
